<?php

namespace App\HttpController;

use App\Service\AuthService;
use App\Utility\Verification;
use EasySwoole\HttpAnnotation\AnnotationTag\Api;
use EasySwoole\HttpAnnotation\AnnotationTag\ApiDescription;
use EasySwoole\HttpAnnotation\AnnotationTag\ApiGroup;
use EasySwoole\HttpAnnotation\AnnotationTag\Method;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\Mysqli\Exception\Exception;
use Throwable;

/**
 * @ApiGroup(groupName="安全验证")
 */
class Auth extends BaseController
{
    /**
     * @ApiDescription(value="绑定手机号")
     * @Api(name="绑定手机号", path="/auth/bindPhone", version="1.0.0")
     * @Method(allow={POST})
     * @Param(name="phone", description="手机号", required="手机号不能为空", notEmpty="手机号不能为空", from={JSON})
     * @Param(name="code", description="验证码", required="验证码不能为空", notEmpty="验证码不能为空", from={JSON})
     * @Param(name="requestId", description="验证码匹配任务ID", from={JSON})
     * @return bool
     * @throws Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     */
    public function bindPhone($phone, $code, $requestId): bool
    {

        $checkPhone = Verification::getInstance()->is_phone($phone);
        if (!$checkPhone){
            return $this->writeJsonError('手机号输入错误');
        }
        $ips = $this->request()->getHeaders()['x-real-ip'] ?? [];
        $this->ip = $ips[0] ?? '127.0.0.1';
        $res = AuthService::getInstance()->bindPhone($this->uid, $phone, $code, $requestId, $this->ip);
        if (!$res['result']) {
            return $this->writeJsonError($res['msg']);
        }
        return $this->writeJsonSuccess($res['data'], $res['msg']);
    }
}